const connection = require('../app/database')

class FileService {
  // 插入数据到数据库
  async create(...payload) {

    // 1.获取请求参数
    const [ filename, mimetype, size, user_id ] = payload

    // 2.定义预处理语句
    const statement = 'INSERT INTO `avatar` ( filename, mimetype, size, user_id) VALUES (?, ?, ?, ?);'

    // 3.执行sql语句
    let [res, fields] = await connection.execute(statement, [filename, mimetype, size, user_id])
    return res
  }

  async queryAvatarByUserId(...payload) {

    // 1.获取请求参数
    const [ userId ] = payload

    // 2.定义预处理语句
    const statement = 'SELECT * FROM  avatar WHERE user_id = ?'

    // 3.执行sql语句
    let [res, fields] = await connection.execute(statement, [userId])
    
    // 用户上传的多张图片 获取最新上传的图片
    // return res.pop()
    return res[res.length-1]
  }
}

module.exports = new FileService()